# -*- coding:utf-8 -*-

__author__ = 'ghostviper'

from lxml.etree import _Element
from lxml.html import etree
from base import BaseParser


class XmlParser(BaseParser):

    def __init__(self):
        self.html = None
        self.field_name = None
        self.rule = dict()
        self.et = None
        self.out = "takefirst"

    def field_extract(self, html, field_name, rule):
        self.html = html
        self.et = etree.HTML(html)
        self.field_name = field_name
        self.rule = rule
        method = self.rule.get('method', 'xpath')
        if method == "xpath":
            extract_result = self.lxml_field_extract()
            return extract_result

    def lxml_field_extract(self):
        rules = self.rule.get('extract_rules', tuple())
        out = self.rule.get('out', 'takefirst')
        if isinstance(self.et, _Element):
            output_list = list()
            for rule in rules:
                output_list.append(self.lxml_rule_parser(rule))
            output_result = self.output_callback(output_list)
            return output_result
        else:
            return {}

    def lxml_rule_parser(self, rule):
        for element in self.et.xpath(rule):
            if isinstance(element, _Element):
                return element.text
            elif isinstance(element, str):
                return element

    def output_callback(self, output_list):
        if self.out == "takefirst":
            return {self.field_name: output_list[0]}
        elif self.out == "join":
            return {self.field_name: "".join(output_list)}
